<!-- 小程序banner配置 -->

<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <GzSearchForm
        :searchFunc="searchFunc"
        :resetFunc="() => searchData = {}"
      >
        <GzTextUp v-model:value="searchData['channelCode']" placeholder="员工编号" />
        <GzTextUp v-model:value="searchData['appId']" placeholder="公众号" />
      </GzSearchForm>

      <!-- 列表渲染 -->
      <GzTable
        ref="infoTableRef"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="searchData"
        row-key="activityChannelId"
        :scrollX="800"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_CHANNEL_EMPLOYEE_ADD')" type="primary" @click="addOrEditFunc()">
            <plus-outlined />新建
          </a-button>
          <a-button v-if="$access('ENT_CHANNEL_EMPLOYEE_EXPT')" type="primary" :disabled="total == 0" @click="exportCode">
            <export-outlined />导出渠道码
          </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="$access('ENT_CHANNEL_EMPLOYEE_VIEW') && column.key == 'channelName'">
            <a @click="lookChnnelCode(record)">
              <b>{{ record.channelName }}</b>
            </a>
          </template>
          <template v-if="column.key == 'isDeleted'">
            <GzTableColState
              :state="record.isDeleted === 0 ? 1 : 0"
              :show-switch-type="$access('ENT_CHANNEL_EMPLOYEE_EDIT')"
              :on-change="() => changeStatus(record.activityChannelId,record.isDeleted)"
            />
          </template>
        </template>
      </GzTable>
    </a-card>
    <!-- 新增OR修改 -->
    <AddOrEdit ref="addOrEditRef" :callBackFunc="searchFunc" />

    <a-modal
      v-model:visible="open"
      :footer="null"
      :bodyStyle="{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }"
    >
      <a-image :width="200" :src="codeUrl" />
      <div>{{ vdata.channelRecord.channelCode }}</div>
      <div>{{ vdata.channelRecord.appName }}</div>
      <div>【 {{ useAgentStore().hostname }} 】</div>
    </a-modal>
  </page-header-wrapper>
</template>

<script lang="ts" setup>
import {ref,reactive,getCurrentInstance} from 'vue'
import AddOrEdit from './AddOrEdit.vue'
import { useAgentStore } from '@/store/modules/agent'
const open = ref(false)
const codeUrl = ref('')

import { $getChannelList,$delChannel,$exportChannel } from '@/api/channel/index'
import { generateChannelCode, exportChannelCode } from '@/views/channel/channelUtils'
const { $infoBox, $access } =getCurrentInstance()!.appContext.config.globalProperties

const total = ref(0)
const searchData: any = ref({})
const addOrEditRef = ref()
const infoTableRef = ref()

const vdata: any = reactive({
  stateVisible: false,
  title: '确认关闭？',
  channelRecord: null,  // 选择的渠道记录
})

const tableColumns = [
  { key: 'appId', title: '公众号appId', dataIndex: 'appId' },
  { key: 'appName', title: '公众号名称', dataIndex: 'appName' },
  { key: 'channelCode', title: '渠道编号', dataIndex: 'channelCode' },
  { key: 'channelName', title: '渠道名称', dataIndex: 'channelName' },
  { key: 'createdAt', title: '创建时间', dataIndex: 'createdAt' },
  { key: 'isDeleted', title: '状态', dataIndex: 'isDeleted' }
]
/**
 * 请求渠道列表
 */
function reqTableDataFunc(params: any) {
  return new Promise(async (resolve, reject) => {
    const res = await  $getChannelList( {...searchData.value,...params,channelType:0})
    total.value = res.total
    resolve(res)
  })
}
// 查询
function searchFunc() {
  infoTableRef.value.refTable(true)
}

// 新增
function addOrEditFunc() {
  addOrEditRef.value.show()
}

// 查看渠道码
const lookChnnelCode = async (record) => {
  const url = await generateChannelCode(`${useAgentStore().channelBaseUrl}?channelId=${record.activityChannelId}&channelType=${record.channelType}`)
  codeUrl.value = url
  vdata.channelRecord = record
  open.value = true
}

/**
 * 渠道上下线
 */
function changeStatus(activityChannelId, isDeleted) {
  const title = isDeleted === 1 ? '确认[启用]该渠道？' : '确认[停用]该渠道？'
  const content = isDeleted === 1 ? '启用后该渠道码将可被使用' : '停用后该渠道码将不可被使用'
  return new Promise<void>((resolve, reject) => {
    $infoBox.confirmDanger(
      title,
      content,
      () => {
        return $delChannel({
            activityChannelId,
            isDeleted: isDeleted === 1 ? 0 : 1,
          })
          .then(() => {
            resolve()
            // 刷新列表
            infoTableRef.value.refTable()
          })
          .catch((err) => reject(err))
      },
      () => {
        reject(new Error())
      }
    )
  })
}
async function exportCode() {
  $infoBox.confirmDanger('确认导出？', '请确认是否导出渠道码？', async () => {
    //   // 获取活动渠道列表
    const channelList = await $exportChannel({ ...searchData.value, channelType: 0 })
    exportChannelCode(channelList,0)
  })
}
</script>

<style lang="less" scoped>
.dialog {
  position: relative;
  left: 50%;
  top: -50%;
  transform: translate(-50%);

  z-index: 88;
  // background:red;
}

.table-content {
  padding: 30px 30px 10px 30px;
}

.handle {
  display: flex;
  justify-content: flex-end;

  .button {
    padding: 0;
  }
}

.image-container {
  position: relative;
  width: 100%;

  .banner-order {
    position: absolute;
    bottom: 0;
    right: 0;
    background-color: #f2f2f2;
    font-size: 13px;
    z-index: 10;
    padding: 5px;
  }

  .image {
    position: absolute;
    width: 100%;
    height: 100%;
  }
}
</style>
